﻿using ChikovMF.Application.Common.Exceptions;
using ChikovMF.Application.Common.Interfaces;
using ChikovMF.Application.Features.Files.DeleteFile;
using ChikovMF.Entities;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace ChikovMF.Application.Features.Projects.DeleteProject;

public class DeleteProjectCommandHandler : IRequestHandler<DeleteProjectCommand>
{
    public async Task Handle(DeleteProjectCommand request, CancellationToken cancellationToken)
    {
        var project = await _context.Projects
            .Include(p => p.CardImage)
            .Include(p => p.SliderImages)
            .Include(p => p.Links)
            .FirstOrDefaultAsync(p => p.ProjectId == request.ProjectId, cancellationToken);

        if (project == null)
        {
            throw new NotFoundEntityException(nameof(Project), request.ProjectId);
        }

        if (project.CardImage != null)
        {
            await _fileManager.DeleteFile(project.CardImage.PathLocation, project.CardImage.Name, cancellationToken);
        }

        foreach (var silderImage in project.SliderImages!)
        {
            await _fileManager.DeleteFile(silderImage.PathLocation, silderImage.Name, cancellationToken);
        }

        _context.Projects.Remove(project);
        await _context.SaveChangesAsync(cancellationToken);
    }

    private readonly IChikovMFContext _context;
    private readonly IFileManager _fileManager;
    public DeleteProjectCommandHandler(IChikovMFContext context, IFileManager fileManager)
    {
        _context = context;
        _fileManager = fileManager;
    }
}
